// pages/search/search.js
import {searchConsultants,searchArticles} from '../../api/search'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchValue: '', // 搜索框内容
    hasSearched: false, // 是否已搜索
    currentTab: 'all', // 当前标签页
    searchHistory: [], // 搜索历史
    searchResult: {
      consultants: [],
      articles: []
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 从本地存储加载搜索历史
    this.loadSearchHistory();
  },
  // 加载搜索历史
  loadSearchHistory() {
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({
      searchHistory: history
    });
  },

  // 输入框输入事件
  onInput(e) {
    this.setData({
      searchValue: e.detail.value
    });
  },

  // 搜索事件
  async onSearch() {
    const keyword = this.data.searchValue.trim();
    if (!keyword) {
      wx.showToast({ title: '请输入搜索内容', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '搜索中...' });

    try {
      // 并行调用两个搜索接口
      const [consultantResult, articleResult] = await Promise.all([
        searchConsultants(keyword, 1, 10),
        searchArticles(keyword, 1, 10)
      ]);

      wx.hideLoading();
      
      // 添加到搜索历史
      this.addToHistory(keyword);
      
      // 更新搜索结果
      this.setData({
        hasSearched: true,
        searchResult: {
          keyword: keyword,
          consultants: consultantResult.list || [],
          consultantTotal: consultantResult.total || 0,
          articles: articleResult.list || [],
          articleTotal: articleResult.total || 0
        }
      });
      
    } catch (err) {
      wx.hideLoading();
      console.error('搜索失败:', err);
    }
  },
  // 添加到搜索历史
  addToHistory(keyword) {
    let history = this.data.searchHistory;
    
    // 移除已存在的相同关键词
    history = history.filter(item => item !== keyword);
    
    // 添加到开头
    history.unshift(keyword);
    
    // 限制历史记录数量
    if (history.length > 10) {
      history = history.slice(0, 10);
    }

    this.setData({
      searchHistory: history
    });

    // 保存到本地存储
    wx.setStorageSync('searchHistory', history);
  },
  // 填充搜索框
  fillSearch(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      searchValue: keyword
    });
  },

  // 删除单条历史记录
  deleteHistory(e) {
    const index = e.currentTarget.dataset.index;
    let history = this.data.searchHistory;
    history.splice(index, 1);
    
    this.setData({
      searchHistory: history
    });
    
    wx.setStorageSync('searchHistory', history);
  },
  // 清空搜索历史
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            searchHistory: []
          });
          wx.setStorageSync('searchHistory', []);
        }
      }
    });
  },
    // 切换标签页
    async switchTab(e) {
      const tab = e.currentTarget.dataset.tab;
      const keyword = this.data.searchValue.trim();
      
      if (!keyword) {
        wx.showToast({
          title: '请输入搜索内容',
          icon: 'none'
        });
        return;
      }
      wx.showLoading({ title: '搜索中...' });
  
      try {
        let consultantResult = { list: [], total: 0 };
        let articleResult = { list: [], total: 0 };
  
        // 根据标签页决定调用哪些接口
        if (tab === 'all' || tab === 'consultant') {
          consultantResult = await searchConsultants(keyword, 1, 10);
        }
        if (tab === 'all' || tab === 'article') {
          articleResult = await searchArticles(keyword, 1, 10);
        }
  
        wx.hideLoading();
        
        this.setData({ 
          currentTab: tab,
          searchResult: {
            consultants: consultantResult.list || [],
            consultantTotal: consultantResult.total || 0,
            articles: articleResult.list || [],
            articleTotal: articleResult.total || 0
          }
        });
      } catch (err) {
        wx.hideLoading();
        console.error('搜索失败:', err);
      }
    },

    // 查看文章详情
    viewArticleDetail(e) {
      const articleId = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: `/pages/indexdetail/indexdetail?id=${articleId}`
      });
    },
  
    // 查看咨询师详情
    viewConsultantDetail(e) {
      const consultantId = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: `/pages/teacherdetail/teacherdetail?id=${consultantId}`
      });
    },
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})